<?php
class Zend_View_Helper_Fck extends Zend_View_Helper_Abstract
{
    protected $_enabled = false;
    
    protected $_name = 'fck';
    protected $_config = array ('toolbar' => 'Basic' );
    protected $_scriptPath;
    protected $_scriptFile;

    public function __set($name, $value)
    {
        $method = 'set' . $name;
        if (! method_exists ( $this, $method ))
        {
            throw new Sozfo_View_Exception ( 'Invalid FCK property' );
        }
        $this->$method ( $value );
    }

    public function __get($name)
    {
        $method = 'get' . $name;
        if (! method_exists ( $this, $method ))
        {
            throw new Sozfo_View_Exception ( 'Invalid FCK property' );
        }
        return $this->$method ();
    }

    public function setName($name)
    {
        $this->_name = $name;
    }

    public function setOptions(array $options)
    {
        $methods = get_class_methods ( $this );
        foreach ( $options as $key => $value )
        {
            $method = 'set' . ucfirst ( $key );
            if (in_array ( $method, $methods ))
            {
                $this->$method ( $value );
            }
            elseif (in_array ( $method, $this->_config ))
            {
                $this->_config [$key] = $value;
            }
        }
        return $this;
    }

    public function Fck()
    {
        return $this;
    }

    public function setScriptPath($path)
    {
        $this->_scriptPath = rtrim ( $path, '/' );
        return $this;
    }

    public function setScriptFile($file)
    {
        $this->_scriptFile = ( string ) $file;
    }

    public function render()
    {
        //if (false === $this->_enabled)
        {
            $this->_renderScript ();
            $this->_renderEditor ();
        }
        $this->_enabled = true;
    }

    protected function _renderScript()
    {
        $this->view->headScript ()->appendFile ( $this->view->baseUrl () . $this->_scriptPath . '/' . $this->_scriptFile );
        return $this;
    }

    protected function _renderEditor()
    {
        $params = array ();
        foreach ( $this->_config as $name => $value )
        {
            if (is_array ( $value ))
            {
                $value = implode ( ',', $value );
            }
            if (! is_bool ( $value ))
            {
                $value = '"' . $value . '"';
            }
            $params [] = $name . ' : ' . $value;
        }
        $script = implode ( ',' . PHP_EOL, $params ) . PHP_EOL;
        
        $scr = "//window.onload = function()
                { 
                    CKEDITOR.replace( '" . $this->_name . "',
                    {
                        $script
                    } );
                };";
        
        $this->view->headScript ()->appendScript ( $scr );
        return $this;
    }
}
